﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.IO;
using System.Configuration;

namespace BackupTool
{
#pragma warning disable 0618 //System.Configuration.ConfigurationSettings.AppSettings
    class Program
    {
        static MemoryStream dest;
        static string fileSource = ConfigurationSettings.AppSettings["fileDirectory"];
        static string fileName = ConfigurationSettings.AppSettings["fileName"];
        static string fileExt = ConfigurationSettings.AppSettings["fileExt"];
        static string fileDestination = ConfigurationSettings.AppSettings["fileDestination"];
        static int frequency = 1000 * Int32.Parse(ConfigurationSettings.AppSettings["frequency"]);
        static int maxBackups = Int32.Parse(ConfigurationSettings.AppSettings["maxBackups"]);

        static void Main(string[] args)
        {
            try
            {
                Thread copyThread = new Thread(new ThreadStart(CopyPasteThreadClass.run));
                copyThread.Start();
            }
            catch (FileNotFoundException e)
            {
                Console.WriteLine(e.Message);
            }
            catch (DirectoryNotFoundException e)
            {
                Console.WriteLine(e.Message);
            }
        }

        class CopyPasteThreadClass
        {
            public static void run()
            {
                while (frequency > 0)
                {
                    Thread.Sleep(frequency);
                    copyPasta();
                    maintainFolder();
                }
            }
        }
        /// <summary>
        /// Copies from source file to a new renamed backup
        /// </summary>
        static void copyPasta()
        {
            dest = new MemoryStream();
            byte[] bytes;

            string ts = DateTime.Now.ToLongTimeString();
            string timeStamp = DateTime.Now.ToShortDateString() + "  " + ts.Substring(0, 2) + "." + ts.Substring(3, 2) + "." + ts.Substring(6);

            using (FileStream fs = File.Open(fileSource + fileName + fileExt, FileMode.Open))
            {
                fs.CopyTo(dest);
                bytes = dest.ToArray();
            }
            using (FileStream fs = File.Create(fileDestination + "BACKUP " + timeStamp + "  " + fileName + fileExt))
            {
                fs.Write(bytes, 0, bytes.Length);
                Console.WriteLine("Backup Created  " + DateTime.Now.ToString());
            }
        }
        /// <summary>
        /// Compares time of creation of elements in the backup folder and deletes the oldest files
        /// </summary>
        static void maintainFolder()
        {
            List<string> filePaths = new List<string>();
            DateTime compareDate = new DateTime();
            string oldestFilePath = null;


            foreach (string s in Directory.GetFiles(fileDestination)) //get all files with fileExt and the BACKUP tag
            {
                FileInfo finfo = new FileInfo(s);

                if (finfo.Name.Substring(0, 6).Equals("BACKUP") && finfo.Extension.Equals(fileExt))
                {
                    filePaths.Add(s);
                }
            }

            Random r = new Random();

            while (maxBackups < filePaths.Count)
            {
                while (oldestFilePath == null) //choose an initial comparison date and make sure it is not null
                {
                    int rr = r.Next(maxBackups);
                    compareDate = File.GetCreationTime(filePaths[rr]);
                    oldestFilePath = filePaths[rr];
                }

                foreach (string fn in filePaths) //compare dates
                {
                    //if t1 is earlier than t2 then the int returned is less than zero
                    if (0 > DateTime.Compare(File.GetCreationTime(fn), compareDate))
                    {
                        compareDate = File.GetCreationTime(fn);
                        oldestFilePath = fn;
                    }
                }
                File.Delete(oldestFilePath);
                filePaths.Remove(oldestFilePath);
                oldestFilePath = null;
            }
        }
    }
}
